package com.ejlchina.tool.util

import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.os.ParcelUuid
import android.util.Log
import com.ejlchina.tool.MyApplication
import java.util.UUID

object BleScan {
    val bluetoothManager: BluetoothManager = MyApplication.instance.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
    val bluetoothAdapterPre: BluetoothAdapter? = bluetoothManager.adapter
    val bluetoothAdapter: BluetoothAdapter
        get() = bluetoothAdapterPre!!

    private val bluetoothLeScanner = bluetoothAdapter.bluetoothLeScanner
    var isScanning = false

    // Stops scanning after 10 seconds.
    private val SCAN_PERIOD: Long = 10000

    @SuppressLint("MissingPermission")
    fun scanLeDevice() {
//        if (!isScanning) {
//            bluetoothLeScanner.startScan(getScanFilters(BLUETOOTH_NAME), getScanSettings(), scanCallback)
            bluetoothLeScanner.startScan(object :ScanCallback(){
                override fun onScanResult(callbackType: Int, result: ScanResult?) {
                    super.onScanResult(callbackType, result)
                    Log.i("Hengliang",result?.device?.address.toString())
                }

                override fun onBatchScanResults(results: MutableList<ScanResult>?) {
                    super.onBatchScanResults(results)
                    Log.i("Hengliang",results.toString())
                }

                override fun onScanFailed(errorCode: Int) {
                    super.onScanFailed(errorCode)
                }

            })
            isScanning = true
//        }
    }

    @SuppressLint("MissingPermission")
    fun stopScan(scanCallback: ScanCallback){
        bluetoothLeScanner.stopScan(scanCallback)
    }


    fun getScanFilters(name: String): MutableList<ScanFilter>{
//        return mutableListOf(ScanFilter.Builder().setServiceUuid(ParcelUuid(serviceUUID)).build())
//        return mutableListOf(ScanFilter.Builder().build())
        return mutableListOf(ScanFilter.Builder().setDeviceName(name).build())
    }

    fun getScanSettings(): ScanSettings{
        return ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_POWER).setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES).build()
    }
}